<template>
  <div class="container">
    <h2>喂养记录管理</h2>
    <button @click="showForm = true" class="add-button">新增记录</button>
    
    <div v-if="showForm" class="form-overlay">
      <div class="form-container">
        <h3>{{ newRecord.id ? '编辑' : '新增' }}喂养记录</h3>
        <form @submit.prevent="submitRecord">
          <div class="form-group">
            <h4>喂奶日期</h4>
            <input type="date" v-model="newRecord.date" required class="date-input">
          </div>
          <div class="form-group">
            <h4>喂奶时间</h4>
            <input type="time" v-model="newRecord.time" required class="time-input">
          </div>
          <div class="form-group">
            <h4>喂奶量(ml)</h4>
            <input type="number" v-model="newRecord.amount" required class="amount-input" placeholder="请输入毫升数">
          </div>
          <div class="button-group">
            <button type="button" @click="showForm = false">取消</button>
            <button type="submit" :disabled="isSubmitting">
              {{ isSubmitting ? '提交中...' : '提交' }}
            </button>
          </div>
        </form>
      </div>
    </div>

    <div class="pagination-controls">
      <select v-model="itemsPerPage" @change="currentPage = 1">
        <option v-for="option in pageSizeOptions" :value="option" :key="option">
          每页 {{ option }} 条
        </option>
      </select>
      
      <div class="pagination">
        <button @click="currentPage = Math.max(1, currentPage - 1)" :disabled="currentPage === 1">
          上一页
        </button>
        <span>第 {{ currentPage }} / {{ totalPages }} 页</span>
        <button @click="currentPage = currentPage + 1" :disabled="currentPage >= totalPages">
          下一页
        </button>
      </div>
      
      <div class="jump-to-page">
        <span>跳转到日期</span>
        <div class="date-picker-container">
          <button @click="toggleDatePicker" class="date-picker-btn">
            选择日期 ▼
          </button>
          <div v-if="showDatePicker" class="date-picker-dropdown">
            <div class="date-picker-header">有记录的日期</div>
            <div class="date-list">
              <div 
                v-for="date in availableDates" 
                :key="date"
                @click="goToDatePage(date)"
                class="date-item"
              >
                {{ formatDate(date) }}
                <span class="record-count">
                  ({{ records.filter(r => r.date === date).length }}条记录)
                </span>
              </div>
            </div>
            <div v-if="availableDates.length === 0" class="no-dates">
              暂无记录
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <div class="record-list">
      <template v-for="(record, index) in paginatedRecords" :key="record.id">
        <div v-if="shouldShowDateDivider(record, index)" class="date-divider">
          {{ formatDate(record.date) }} (总喂奶量: {{ 
            records
              .filter(r => isSameDate(r.date, record.date))
              .reduce((sum, r) => sum + r.amount, 0) 
          }}ml)
        </div>
        <div class="record-item">
          <div class="record-time">{{ record.time }}</div>
          <div class="record-amount">{{ record.amount }}ml</div>
          <button @click="editRecord(record)" class="edit-btn">编辑</button>
          <button @click="deleteRecord(record.id)" class="delete-btn">删除</button>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, h, getCurrentInstance, onUnmounted } from 'vue'
import axios from 'axios'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'


const records = ref([])
const showForm = ref(false)
const newRecord = ref({
  id: null,
  date: dayjs().format('YYYY-MM-DD'),
  time: dayjs().format('HH:mm'),
  amount: ""
})
const currentPage = ref(1)
const itemsPerPage = ref(50)
const pageSizeOptions = [10, 50, 100]
const jumpToDate = ref('')
const showDatePicker = ref(false)
const isSubmitting = ref(false)

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(records.value.length / itemsPerPage.value)
})

// 计算所有有记录的日期
const availableDates = computed(() => {
  const dates = [...new Set(records.value.map(record => record.date))]
  return dates.sort((a, b) => new Date(b) - new Date(a)) // 按日期降序排列
})


// 计算当前页的记录
const paginatedRecords = computed(() => {
  const startIndex = (currentPage.value - 1) * itemsPerPage.value
  const endIndex = startIndex + itemsPerPage.value
  return records.value.slice(startIndex, endIndex)
})

// 判断是否应该显示日期分隔条
const shouldShowDateDivider = (record, index) => {
  // 获取当前记录在完整记录列表中的索引
  const recordIndex = records.value.findIndex(r => r.id === record.id)
  
  // 如果是第一条记录，或者与前一条记录日期不同，则显示日期分隔条
  return recordIndex === 0 || !isSameDate(record.date, records.value[recordIndex - 1].date)
}

const formatDate = (date) => dayjs(date).format('YYYY-MM-DD')
const isSameDate = (date1, date2) => dayjs(date1).isSame(dayjs(date2), 'day')

onMounted(getdata)
async function getdata(){
  try {
    const response = await axios.get(`${import.meta.env.VITE_API_BASE_URL}/api/records`)
    records.value = response.data
  } catch (error) {
    console.error('获取记录失败:', error)
  }
}
const submitRecord = async () => {
  // 防止重复提交
  if (isSubmitting.value) {
    ElMessage.warning('正在提交中，请勿重复点击')
    return
  }

  // 表单验证
  if (!newRecord.value.amount || newRecord.value.amount <= 0) {
    ElMessage.warning('请输入有效的喂奶量')
    return
  }

  isSubmitting.value = true
  
  try {
    const payload = {
      ...newRecord.value
    }
    let response
    if (newRecord.value.id) {
      response = await axios.put(`${import.meta.env.VITE_API_BASE_URL}/api/records/${newRecord.value.id}`, payload)
      const index = records.value.findIndex(r => r.id === newRecord.value.id)
      if (index !== -1) records.value.splice(index, 1, response.data)
      ElMessage.success('修改成功')
    } else {
      response = await axios.post(`${import.meta.env.VITE_API_BASE_URL}/api/records`, payload)
      ElMessage.success('新增成功')
    }
    
    await getdata() // 等待数据刷新完成
    
    showForm.value = false
    newRecord.value = {
      id: null,
      date: dayjs().format('YYYY-MM-DD'),
      time: dayjs().format('HH:mm'),
      amount: ""
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败，请重试')
  } finally {
    isSubmitting.value = false
  }
}

// console.log(import.meta.env.PROD,"生产")
// console.log(import.meta.env.VITE_API_BASE_URL)

const editRecord = (record) => {
  newRecord.value = {
    id: record.id,
    date: record.date,
    time: record.time,
    amount: record.amount
  }
  showForm.value = true
}

const deleteRecord = async (id) => {
  if (!confirm('确定要删除这条记录吗？')) return
  
  try {
    await axios.delete(`${import.meta.env.VITE_API_BASE_URL}/api/records/${id}`)
    records.value = records.value.filter(record => record.id !== id)
  } catch (error) {
    console.error('删除失败:', error)
  }
}

// 跳转到指定日期所在页
const goToDatePage = (targetDate) => {
  // 查找指定日期的第一条记录在列表中的索引
  const recordIndex = records.value.findIndex(record => record.date === targetDate)
  
  if (recordIndex === -1) {
    ElMessage.warning('该日期没有喂养记录')
    return
  }
  
  // 计算该记录所在的页码
  const targetPage = Math.floor(recordIndex / itemsPerPage.value) + 1
  currentPage.value = targetPage
  showDatePicker.value = false
  ElMessage.success(`已跳转到${targetDate}所在页面`)
}

// 切换日期选择器显示状态
const toggleDatePicker = () => {
  showDatePicker.value = !showDatePicker.value
}

// 点击外部关闭日期选择器
const handleClickOutside = (event) => {
  const datePickerContainer = event.target.closest('.date-picker-container')
  if (!datePickerContainer && showDatePicker.value) {
    showDatePicker.value = false
  }
}

// 添加和移除事件监听
onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
.container {
  padding: 15px;
  margin-top: 10px;
  margin-bottom: 60px; /* 为底部导航栏留出空间，调整为60px以适应导航栏 */
}

h2 {
  font-size: 36px;
  margin-bottom: 25px;
  text-align: center;
  color: #2c3e50;
}

.add-button {
  background: #4CAF50;
  color: white;
  padding: 15px 20px;
  border: none;
  border-radius: 8px;
  margin-bottom: 20px;
  width: 100%;
  font-size: 20px;
  font-weight: bold;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.form-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.form-container {
  background: white;
  padding: 20px;
  border-radius: 12px;
  width: 90%;
  max-width: 350px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.form-container h3 {
  color: #333;
  font-size: 32px;
  margin-bottom: 25px;
  text-align: center;
}

.form-group {
  margin-bottom: 15px;
}

.form-group h4 {
  margin: 8px 0;
  font-size: 20px;
  color: #333;
}

.date-input,
.time-input,
.amount-input {
  width: 100%;
  padding: 12px 15px;
  font-size: 18px;
  border: 1px solid #ddd;
  border-radius: 8px;
  box-sizing: border-box;
}

.amount-input {
  margin-bottom: 15px;
}

.button-group {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

.button-group button {
  flex: 1;
  padding: 15px 0;
  border-radius: 8px;
  font-size: 20px;
  font-weight: bold;
}

.button-group button[type="button"] {
  background-color: #f5f5f5;
  color: #333;
  border: 1px solid #ddd;
}

.button-group button[type="submit"] {
  background-color: #4CAF50;
  color: white;
  border: none;
}

.button-group button[type="submit"]:disabled {
  background-color: #cccccc;
  color: #666666;
  cursor: not-allowed;
  opacity: 0.6;
}

.record-list {
  background: white;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.record-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.record-time {
  font-size: 18px;
  color: #666;
}

.record-amount {
  font-size: 20px;
  font-weight: bold;
  color: #42b883;
}

.edit-btn {
  color: #2196F3;
  border: none;
  background: none;
  padding: 8px;
  font-size: 18px;
}

.delete-btn {
  color: #ff4444;
  border: none;
  background: none;
  padding: 8px;
  font-size: 18px;
}

.date-divider {
  padding: 12px 15px;
  font-weight: bold;
  font-size: 20px;
  color: #333;
  background-color: #f0f8f0;
  border-left: 4px solid #4CAF50;
}

.pagination-controls {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 20px;
}

.pagination-controls select {
  padding: 12px;
  border-radius: 8px;
  border: 1px solid #ddd;
  font-size: 18px;
  background-color: white;
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: white;
  border-radius: 8px;
  padding: 5px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.pagination button {
  padding: 12px 15px;
  border: none;
  border-radius: 6px;
  background: #f5f5f5;
  color: #333;
  font-size: 18px;
  font-weight: bold;
}

.pagination span {
  font-size: 18px;
  color: #666;
}

.pagination button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  color: #999;
}

.jump-to-page {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  background: white;
  border-radius: 8px;
  padding: 12px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.jump-to-page span {
  font-size: 16px;
  color: #666;
}

.page-input {
  width: 60px;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  text-align: center;
  font-size: 16px;
}

.jump-btn {
  padding: 8px 12px;
  border: none;
  border-radius: 4px;
  background: #4CAF50;
  color: white;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
}

.jump-btn:hover {
  background: #45a049;
}

/* 日期选择器样式 */
.date-picker-container {
  position: relative;
  display: inline-block;
}

.date-picker-btn {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
  color: #333;
  font-size: 16px;
  cursor: pointer;
  min-width: 120px;
}

.date-picker-btn:hover {
  background: #f5f5f5;
}

.date-picker-dropdown {
  position: absolute;
  top: 100%;
  right: 0;
  background: white;
  border: 1px solid #ddd;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  max-height: 250px;
  overflow-y: auto;
  margin-top: 4px;
  width: 200px;
}

.date-picker-header {
  padding: 6px 8px;
  background: #f8f9fa;
  border-bottom: 1px solid #eee;
  font-weight: bold;
  font-size: 11px;
  color: #666;
}

.date-list {
  max-height: 200px;
  overflow-y: auto;
}

.date-item {
  padding: 6px 8px;
  cursor: pointer;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 13px;
  line-height: 1.3;
  gap: 4px;
}

.date-item:hover {
  background: #f8f9fa;
}

.date-item:last-child {
  border-bottom: none;
}

.record-count {
  font-size: 9px;
  color: #666;
  background: #e9ecef;
  padding: 1px 3px;
  border-radius: 6px;
  white-space: nowrap;
  flex-shrink: 0;
  min-width: fit-content;
}

.no-dates {
  padding: 20px;
  text-align: center;
  color: #999;
  font-size: 14px;
}
</style>